package cn.ivicar.oss.filter;

import cn.com.carsmart.exception.CarsmartException;
import cn.ivicar.oss.controller.LoginController;
import cn.ivicar.oss.guice.OssGuiceConfig;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录请求过滤器，对登录操作进行检查和预处理
 * Created by Administrator on 2017/7/5.
 */
public class LoginFilter implements Filter {

    private static LoginController loginController = OssGuiceConfig.getStaticInjector()
            .getInstance(LoginController.class);

    /*
    过滤器实现主方法
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Cookie[] cookies = request.getCookies();//获取客户端提交的所有Cookie
        boolean tag = false;
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if ("sessionId".equalsIgnoreCase(c.getName())) {//忽略大小写的比较
                    tag = true;
                    String sessionId = c.getValue();//Session 对象存储特定用户会话所需的属性及配置信息
                    try {
                        boolean islogin = loginController.isLogin(sessionId);//此处返回false
                        if (!islogin) {
                            response.setStatus(301);
                            response.sendRedirect("/oss-ws/page-login.html");//页面跳转
                        }
                    } catch (CarsmartException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (!tag) {
            response.setStatus(301);
            response.sendRedirect("/oss-ws/page-login.html");
        }
        chain.doFilter(request, response);//执行过滤
    }

    /*
    过滤器的初始化
     */
    public void init(FilterConfig config) throws ServletException {

    }

    /*
    过滤器的销毁
     */
    public void destroy() {
    }

}
